<?php
/**
 * Created by PhpStorm.
 * User: xuleit
 * Date: 2016/11/2
 * Time: 20:32
 */

require_once(LIB_PATH.'controller/root.con.php');
$tableCommentFile = LIB_PATH.'model/tablecomment.model.php';
if(file_exists($tableCommentFile)) require_once( $tableCommentFile );

class adminCon extends rootCon {
    //$autoTag可以增加任意标签xxx,将自动出现在model文件中,生成一个静态函数：xxxField()，返回数组
    public $adminAutoTag = ['image','noList','noEdit','reason','html','upload'];//后台自动标签
    public $autoTag     = ['hide','skip','noView','json','noLoad','delete'];//前后台都有的标签
    public $noAutoTag = ['foreign','status','search','href','admin','title'];//这些标签不是自动生成的，数组形式特殊
    public $cleared = false;//是否清除过菜单

	//show login page
	public function loginAction(){//产生出cookie里边的vid，并重定向到授权页面，或者是跳转到登录后的首页（分享需要,总是到自己的页面）
        require_once(LIB_PATH."view/admin,login.view.php");
    }
	
		//show login page
	public function logoutAction(){
		mylogin::logout();
		myresponse::redirect("admin,login",5,"您已经安全退出登录");
    }

    public function checkAction(){
        usleep(500);
        $userName = r('FUserName');
        $postPassword = md5(COOKIE_KEY1.p('FPwd').COOKIE_KEY2);

        if(!myrequest::isPost()){
            myresponse::redirect("admin,login");
        }

        $log = new LoginLog();
        $loginTime = date('Y-m-d H:i:s');
        $log->created = $loginTime;
        $ip = myrequest::getIp();
        $log->ip =  $ip;
        $log->ipInfo = myip::getAddresInfo($ip);
        $log->userName = $userName;

        $adminUser = new AdminUser();
        $find =  $adminUser->find([['username',$userName],['pwd',$postPassword]]);
        if($find){
            $log->reason = '登录成功';
            $time= time()+24*3600*7;
            setcookie('u_c_',$adminUser->uid.'ttt__'.$loginTime,$time,'/',COOKIE_DOMAIN);
            setcookie('u_c_key',mylogin::getMd5Pwd($adminUser->uid),$time,'/',COOKIE_DOMAIN);
            $log->save();
            myresponse::redirect("admin,default",0,"登录成功");
        }else{
            $log->reason = '密码或用户名错误';
            $log->save();
            myresponse::redirect("admin,login",1,"用户名或是密码不正确");
        }
    }


    //@todo 将数据库sql/init.sql文件自动导入，并初始化新的用户密码
    public function initAction(){
        if(!IS_ADMIN_SYS) die("not allow update pwd: IS_ADMIN_SYS=false ");
        $lockFile = ROOT_PATH."model/install.lock";

        if(file_exists($lockFile)){
            $db = db();
            $sql = "SELECT * FROM tbl_admin_user WHERE `privileges`='super' ORDER BY uid ASC LIMIT 1";
            $row = $db->getOne($sql);

            die('init error,lock file exists,plz delete it first : '.$lockFile." ");
        }else{
            file_put_contents($lockFile,time());
            $db = db();
            $sql = "SELECT * FROM tbl_admin_user WHERE `privileges`='super' ORDER BY uid ASC LIMIT 1";
            $row = $db->getOne($sql);
            $uid = $row['uid'];
            $src = substr(md5(rand(10000,50000).time()),0,8);
            $pwd = mylogin::getMd5Pwd($src);
            $sql = "UPDATE tbl_admin_user SET pwd='$pwd' WHERE uid=$uid";
            $db->query($sql);

            die("init ok,pwd for <font color=red>{$row['username']}</font> is ".$src);
        }
    }

    public function  passAction(){
    $db= new mydb();
    preg_match("/^([0-9]+)/i",$_COOKIE['u_c_'],$matches);
    $adminId = $matches[1];
    $adminUser = new AdminUser();
    $adminUser->find(['uid',$adminId]);
    require(LIB_PATH."view/admin,pass.view.php");
}

    public function changePassAction(){
        $old = md5(COOKIE_KEY1.p('oldPass').COOKIE_KEY2);
        $new = md5(COOKIE_KEY1.p('newPass').COOKIE_KEY2);
        $db= new mydb();
        preg_match("/^([0-9]+)/i",$_COOKIE['u_c_'],$matches);
        $adminId = $matches[1];

        $adminUser = new AdminUser();
        $find = $adminUser->find([['uid',$adminId]]);

        $log = new LoginLog();
        $loginTime = date('Y-m-d H:i:s');
        $log->created = $loginTime;
        $ip = myrequest::getIp();
        $log->ip =  $ip;
        $log->ipInfo = myip::getAddresInfo($ip);
        $log->userName = $adminUser->username;
        if(!$find || $adminUser->pwd!=$old){
            $log->reason = '修改密码失败，老密码错误';
            $log->save();
            myresponse::redirect("/admin,pass",1,"请输入正确的老密码",false);
        }else{
            $adminUser->pwd = $new;
            $adminUser->updated = date('Y-m-d H:i:s');
            $adminUser->save();

            $log->reason = '修改密码成功';
            $log->save();
            myresponse::redirect("/loginlog,list",1,"密码修改成功",true);

        }
    }


    //login ok
    public function defaultAction(){//产生出cookie里边的vid，并重定向到授权页面，或者是跳转到登录后的首页（分享需要,总是到自己的页面）
        if(!IS_ADMIN_SYS) die('404');
        require_once(LIB_PATH."view/admin,default.view.php");
    }

    private function createEditView($tableName){
        if (defined('IS_ADMIN_SYS') && IS_ADMIN_SYS) {
            $template = file(LIB_PATH . 'view/tpl_admin,edit.view.php');
        } else {
            return false;
        }

        $className = $this->getClassName($tableName);
        $lowerName = strtolower($className);
        require_once(mymodel::getClassFile($tableName));
        $modelObj = new $className();
        $allFields = $modelObj->field();

        $tempEdit = '';
        $tempImages = '';
        foreach($allFields as  $fieldName=> $fieldInfo){

            //@noView
            if(in_array($fieldName,$modelObj->noViewField())) continue;//跳过不显示的内容

            $fieldType = strtoupper($fieldInfo[0]);
            $fieldLen  = $fieldInfo[1];
            $fieldDesc = $fieldInfo[2];
            if(!$fieldDesc) $fieldDesc = $fieldName;
            $reg = "/(.*?)@+/i";
            if(preg_match($reg,$fieldDesc,$match)){
                $fieldDesc = $match[1];
            }
            //初始化赋值
            $tempEdit .= $this->getTidyTemplate(LIB_PATH.'view/tpl_null.view.php',$fieldName,$fieldDesc);

            //@noEdit
            if(in_array($fieldName,$modelObj->noEditField()) ){
                $tempEdit .= $this->getTidyTemplate(LIB_PATH.'view/tpl_noedit.view.php',$fieldName,$fieldDesc);
                continue;
            }



            //数字
            $numberType = ['TINYINT','SMALLINT','MEDIUMINT','INT','BIGINT','DECIMAL','FLOAT','DOUBLE','REAL','BIT','BOOLEAN','SERIAL'];
            if(in_array($fieldType,$numberType)){//数字类型字段
                if($fieldName==$modelObj->key()){//自动增长类型
                    $tempEdit .= $this->getTidyTemplate(LIB_PATH.'view/tpl_autokey.view.php',$fieldName,$fieldDesc);
                }else{//其他数字类型
                    $tempEdit .= $this->getTidyTemplate(LIB_PATH.'view/tpl_number.view.php',$fieldName,$fieldDesc);
                }
            }else if(in_array($fieldName,$modelObj->jsonField())){
                $tempEdit .= $this->getTidyTemplate(LIB_PATH.'view/tpl_json.view.php',$fieldName,$fieldDesc);
            }else if(in_array($fieldName,$modelObj->uploadField())){
                $tempEdit .= $this->getTidyTemplate(LIB_PATH.'view/tpl_upload.view.php',$fieldName,$fieldDesc);
            }else if(in_array($fieldName,$modelObj->htmlField())){//html类型
                $tempEdit .= $this->getTidyTemplate(LIB_PATH.'view/tpl_html.view.php',$fieldName,$fieldDesc);
            }else if( in_array($fieldName,$modelObj->imageField())){//图片
                $tempEdit .=  $this->getTidyTemplate(LIB_PATH.'view/tpl_image.view.php',$fieldName,$fieldDesc);
            }else if($fieldType=='TEXT'){
                $tempEdit .= $this->getTidyTemplate(LIB_PATH.'view/tpl_text.view.php',$fieldName,$fieldDesc);
            }else if($fieldType=='DATETIME'){
                $tempEdit .= $this->getTidyTemplate(LIB_PATH.'view/tpl_datetime.view.php',$fieldName,$fieldDesc);
            }else if( !in_array($fieldName,$modelObj->noViewField())){//其他类型，包括文本
                $tempEdit .= $this->getTidyTemplate(LIB_PATH.'view/tpl_varchar.view.php',$fieldName,$fieldDesc);
            }

        }


        //替换
        $fileContent = '';
        foreach($template as $line){
            $reg = "/TempUpper/i";
            $line = preg_replace($reg,$className,$line);


            $reg = "/templower/i";
            $line = preg_replace($reg,$lowerName,$line);

            $reg = "/tempEdit/i";
            $line = preg_replace($reg,$tempEdit,$line);

            $reg = "/tempImages/i";
            $line = preg_replace($reg,$tempImages,$line);

            $fileContent .= $line;
        }

       $fileName = ROOT_PATH.'/view/'.$lowerName.',edit.view.php';
       $this->saveToFile($fileName,$fileContent);
    }

    private function createDevFile(){

    }

    //@todo 修改overwrite默认值为false
    private function saveToFile($fileName,$fileContent,$overwrite=true){
        if(IS_LINUX) echo"skip save to file on linux ".$fileName."\r\n";

        $pathInfo = pathinfo($fileName);
        $dir = $pathInfo['dirname'];
        if(!file_exists($dir)){
            return false;
        }

        if(($overwrite && file_exists($fileName)) || !file_exists($fileName)){
            file_put_contents($fileName,$fileContent);
        }else{
            echo "skip create {$fileName} <br />";
        }
    }


    private function createListView($tableName){
        if(defined('IS_ADMIN_SYS') && IS_ADMIN_SYS){
            $template = file(LIB_PATH.'view/tpl_admin,list.view.php');
        }else{
            return false;
        }

        $className = $this->getClassName($tableName);
        $lowerName = strtolower($className);
        $fileContent = '';

        //-----------------begin 表头-------------
        require_once(ROOT_PATH."model/{$lowerName}.model.php");
        $modelObj = new $className();//代码提示用
        $allFileds = $modelObj->field();
        $key = $modelObj->key();

        $statusFields = $modelObj->statusField();
        $reasonFields = $modelObj->reasonField();
        $hrefFields =  $modelObj->hrefField();
        $imageFields =  $modelObj->imageField();
        $uploadFields =  $modelObj->uploadField();
        $foreignFields =  $modelObj->foreignField();
        $htmlFields = $modelObj->htmlField();
        $noListFields = $modelObj->noListField();
        $noViewFields = $modelObj->noViewField();
        $jsonFields = $modelObj->jsonField();

        $btns = [];
        //优先显示操作字段表头
        $opTitle = '';
        $normalTitle = '';
        $opTitle .= "<th>编辑</th>\r\n";

        foreach($allFileds as $fieldName=>$fieldDetail){
            if(in_array($fieldName,$htmlFields) || in_array($fieldName,$noListFields) || in_array($fieldName,$noViewFields)){//html内容不显示在列表中
                continue;
            }

            if(!array_key_exists($fieldName,$statusFields)){//普通字段
                $commentDesc = $fieldDetail[2];
                $find = preg_match("/(.*?)@+.*?/i",$commentDesc,$tmpMatch);
                if($find){
                    $desc = $tmpMatch[1];
                }else{
                    $desc = $commentDesc;
                }
                $normalTitle .=  '<th>'.($desc?$desc:$fieldName)."</th>\r\n";
            }else{//操作字段
                $normalTitle .= '<th>'.$modelObj->getFieldDesc($fieldName)."</th>\r\n";
                $fieldInfo = $statusFields[$fieldName];
                $needOp = false;
                foreach($fieldInfo as $val=>$info){
                    if(strtolower(trim($info[1]))=='@admin'){
                        $btns[$fieldName][] = $val;
                        $needOp = true;
                    }
                }
                if($needOp) $normalTitle .= "<th>操作</th>\r\n";
            }
        }//end foreach
        //-------------------end 表头-------------


        //---------------begin 数据行---------------------
        $opData = '';
        $normalData = '';
        $key = $modelObj->key();

        $id = "\$currentList[\$i]['$key']";
        /* $opData .= "<td><a href={$lowerName},edit,".$key.',<?php echo '.$id.'; ?>,pageNum,<?php echo r_int(\'pageNum\');?>'."  class=\"button border-main\" >编辑</a></td>\r\n"; */
		$opData .= $this->getTidyTemplate(LIB_PATH.'view/tpl_list_key.view.php',$fieldName);

        //每一行普通数据
        foreach($allFileds as $fieldName=>$fieldDetail){
            if(in_array($fieldName,$htmlFields) || in_array($fieldName,$noListFields) || in_array($fieldName,$noViewFields)){//html内容不显示在列表中
                continue;
            }

            $val = "\$currentList[\$i][$fieldName]";

            //----@status状态-------
            if($statusFields && array_key_exists($fieldName,$statusFields)) {
                $id = "\$currentList[\$i]['$key']";
                $name = '"'.$fieldName.'Reason".'.$id;
                $op = '';
                if(in_array($fieldName,$reasonFields)){
                    $op = "<textarea  name=<?php echo $name;?> id='<?php echo $name;?>'  style='width:100%;' ></textarea><br>";
                }

                if(is_array($btns[$fieldName])){
                    foreach($btns[$fieldName] as $v){
                        $op .= "\r\n<button class=\"button border-main\" onclick=\"changeStatus('<?php echo ".$id."; ?>','".$fieldName."','".$v."','{$statusFields[$fieldName][$v][0]}',$('#<?php echo $name; ?>').val());\">{$statusFields[$fieldName][$v][0]}</button>";
                    }
                }
                $normalData .= '<?php $val = $currentList[$i][\''.$fieldName.'\']; ?>';
                $normalData .= '<td><span id="'.$fieldName.'__<?php echo '.$id.'; ?>" class="currentStatus<?php echo $val; ?>"><?php echo $statusFields[\''.$fieldName.'\'][$val][0]; ?></span></td>'."\r\n";
                if($op) $normalData .=  '<td>'.$op."\r\n</td>\r\n";
}else if($imageFields && in_array($fieldName,$imageFields)){
                $normalData .= $this->getTidyTemplate(LIB_PATH.'view/tpl_list_image.view.php',$fieldName,$imageFields[$fieldName]);
            }else if($hrefFields && array_key_exists($fieldName,$hrefFields)){
                $normalData .= $this->getTidyTemplate(LIB_PATH.'view/tpl_list_href.view.php',$fieldName,$hrefFields[$fieldName]);
            }else if($foreignFields && array_key_exists($fieldName,$foreignFields)){
                $normalData .= $this->getTidyTemplate(LIB_PATH.'view/tpl_list_foreign.view.php',$fieldName);
            } else if($uploadFields && in_array($fieldName,$uploadFields)){
                $normalData .= $this->getTidyTemplate(LIB_PATH.'view/tpl_list_upload.view.php',$fieldName);
            }else if($jsonFields && in_array($fieldName,$jsonFields)){
                $normalData .= $this->getTidyTemplate(LIB_PATH.'view/tpl_list_json.view.php',$fieldName);
            } else{
                $normalData .= $this->getTidyTemplate(LIB_PATH.'view/tpl_list_text.view.php',$fieldName);
            }
        }//end 普通数据
        //-------------------end 数据行-------------



        //替换
        foreach($template as $line){
            $reg = "/TempTh/";
            $line = preg_replace($reg,$opTitle.$normalTitle,$line);

             $reg = "/TempTd/";
            $line = preg_replace($reg,$opData.$normalData,$line);

            $reg = "/TempUpper/";
            $line = preg_replace($reg,$className,$line);


            $reg = "/templower/";
            $line = preg_replace($reg,$lowerName,$line);

            $fileContent .= $line;
        }

        $fileName = ROOT_PATH.'/view/'.$lowerName.',list.view.php';
        $this->saveToFile($fileName,$fileContent);
    }

    private function createCon($tableName){
        $className = $this->getClassName($tableName);
        $lowerName = strtolower($className);
        $fileContent = '';

        //---------------开始生成控制器-------
        if(defined('IS_ADMIN_SYS') && IS_ADMIN_SYS){
            $template = file(LIB_PATH.'controller/admin/tpl_admin.con.php');
        }else{
            $template = file(LIB_PATH.'controller/front/tpl_front.con.php');
        }

        foreach($template as $line){
            $reg = "/TempUpper/";
            $line = preg_replace($reg,$className,$line);


            $reg = "/templower/";
            $line = preg_replace($reg,$lowerName,$line);

            $fileContent .= $line;
        }

        $fileName = ROOT_PATH.'/controller/'.$lowerName.'.con.php';
        $this->saveToFile($fileName,$fileContent);
    }

    private function getAllTables(){
        $db = db();
        $sql = 'SHOW TABLES';
        $result = $db->query($sql);
        $allTables = [];
        for($i = 0; $i < count($result); $i++) {
            if($result[$i]['Tables_in_' . DB_NAME]=='tbl_table_comment')continue;//skip system table

            $allTables[] = $result[$i]['Tables_in_' . DB_NAME];
        }
        return $allTables;
    }

    private function getClassName($tableName){
        return mymodel::getClassName($tableName);
    }

    private function getTableName($createSql){
        $reg = "/CREATE TABLE `(.*?)`.*?'/is";
        if(preg_match($reg,$createSql,$match)){
            return $match[1];
        }
    }

    //@menu for admin
    private function createMenu($createSql){
        //假设tablemenu.model.php文件有错误，先删除它，然后运行两次model,create
        if(!file_exists(ROOT_PATH.'model/tablemenu.model.php')) return false;
        if(!file_exists(ROOT_PATH.'model/tablemenuext.model.php')) return false;

        $this->clearMenu();
        $tableName = $this->getTableName($createSql);

        $reg = "/@menu(.*?)[';]+/is";
        if(preg_match_all($reg,$createSql,$matches)){
            foreach($matches[1] as $match){
                $tmp = preg_split("/::|：：/i",$match);
                $info = array_values(array_filter($tmp));

                if(count($info)==2){
                    $idx  = 0;
                    $mainName = $info[0];
                    $subName  = $info[1];
                }else if(count($info)>=3){
                    $idx      = intval($info[0]);
                    $mainName = $info[1];
                    $subName  = $info[2];
                }else{
                    echo "---begin----@menu error:".$tableName."------- <br>";
                    print_r ($info);
                    echo "---end----@menu error:".$tableName."------- <br><br>";
                }

                $menu = new TableMenu();
                $menu->find([['tableName',$tableName],['mainName',$mainName]]);
                $menu->tableName = $tableName;
                $menu->idx = $idx;
                $menu->mainName = $mainName;
                $menu->subName  = $subName;
                $menu->status   = STATUS_PUBLISH;
                $menu->save();
            }
        }//end if
    }

    private function clearMenu(){
        if($this->cleared){
            return false;
        }

        $sql = 'TRUNCATE TABLE tbl_table_menu';
        $db = db();
        $db->query($sql);
        $this->cleared = true;
    }

    private function createModel($tableName){
        $createSql = $this->getCreateSql($tableName);
        $className = $this->getClassName($tableName);

        $reg = "/`(\w+)`\s?([a-z]+)\(?(\d*?)\)?[\s\,]+(.*?)[\n\r]+/i";
        preg_match_all($reg,$createSql,$matches);
        $fieldInfo = [];
        $allField = '';
        $noLoad = '';
        $noList = '';
        $imageField = '';
        $statusField = [];
        $htmlField = '';
        $foreignField = [];//类似外键的支持
        $titleField = []; //存放的是名称字段，用于后台
        $jiekouInfo = [];
        $allFieldsDesc = [];
        $searchField = [];
        $contentDev = '';
        $tagField = [];
        for($k = 0; $k < count($matches[0]); $k++){
            $this->createMenu($createSql);
            if(!IS_WINDOWS) continue;
            $fName   = $matches[1][$k];
            $fType   = strtoupper($matches[2][$k]);
            $len     = intval($matches[3][$k]);
            $defaultAndComment = $matches[4][$k];
            $reg = "/@(\w+)(.*?)([;\'\"]+)/i";
            $find = preg_match_all($reg,$defaultAndComment,$matchTags);
            foreach( $matchTags[1] as $tag){
                if($tag){
                    $tagField[$tag][] = $fName;
                }
            }

            $regV = "/DEFAULT\s+(.*?)[\,\s]+/i";
            preg_match($regV,$defaultAndComment,$matchV);

            $v = strtoupper($matchV[1]);
            if($v=='CURRENT_TIMESTAMP'){
                $allField   .= "\r\n\tprivate $".$fName."= 'CURRENT_TIMESTAMP';";
                $tempValue = 'CURRENT_TIMESTAMP';
            }else if($v=='NULL'){
                $reg = "/@json/i";
                if(preg_match($reg,$defaultAndComment)){
                    $allField   .= "\r\n\tprivate $".$fName."= [];";
                }else{
                    $allField   .= "\r\n\tprivate $".$fName."= NULL;";
                }
                $tempValue = "";
            }else if(preg_match("/\'/",$v)){//固定值
                $tmpV = str_replace("'","",$matchV[1]);
                $allField   .= "\r\n\tprivate $".$fName."= \"".$tmpV."\";";
                $tempValue = $tmpV;
            }else{
                $reg = "/@json/i";
                if(preg_match($reg,$defaultAndComment)) {
                    $allField .= "\r\n\tprivate $" . $fName . "= [];";
                }else{
                    $allField   .= "\r\n\tprivate $".$fName."= '';";
                }
                $tempValue = "";
            }


            $regComment = "/COMMENT \'(.*?)\'/i";
            $find = preg_match($regComment,$defaultAndComment,$matchComment);
            if($find){
                $comment = preg_replace("/\"/","",$matchComment[1]);
            }else{
                $comment = '';
            }
            $fieldInfo[$fName] = [$fType,$len,$comment];
            $allField   .= "//".$matchComment[1];


            $contentDev .= "\r\n{$matchComment[1]}<input name=\"$fName\" placeholder=\"{$matchComment[1]}\" value=\"$tempValue\"><br />";

            //---desc 字段的含义----
            $regDesc = "/(.*?)@+/";
            $find = preg_match($regDesc,$comment,$matchDesc);
            if($find){
                $desc = preg_replace("/\"/","",$matchDesc[1]);
            }else{
                $desc = $comment;
            }
            if(!$desc) $desc = $fName;
            $allFieldsDesc[$fName] =$desc;

            //---skip load,for safety---
            $regSkip = "/@noload/i";
            if(preg_match($regSkip,$defaultAndComment)){
                $noLoad .= "\r\n\t\t\t".'\''.$fName.'\',';
            }
            //---skip list---
            $regList = "/@noList/i";
            if(preg_match($regList,$defaultAndComment)){
                $noList .= "\r\n\t\t\t".'\''.$fName.'\',';
            }

            //---image field----
            $regImg = "/@image/i";
            if(preg_match($regImg,$defaultAndComment)){
                $imageField .= "\r\n\t\t\t".'\''.$fName.'\',';
            }




            //---html field----
            $regHtml = "/@html/i";
            if(preg_match($regHtml,$defaultAndComment)){
                $htmlField .= "\r\n\t\t\t".'\''.$fName.'\',';
            }


            $regStatus = "/@status/i";//@todo 重构，只用二级的数组
            $commentSrc = $defaultAndComment;
            $findStatus = preg_match($regStatus,$commentSrc);
            if(!$findStatus){
                $tc = new TableComment();
                $find = $tc->find([['tableName'=>$tableName],['fieldName'=>$fName]]);
                if($find){
                    $commentSrc = $tc->comment;
                }
                $findStatus = preg_match($regStatus,$commentSrc);
            }

            if($findStatus){
                $statusSrc = str_replace("'","",$commentSrc);
                $statusSrc = str_replace(",","",$statusSrc);
                $statusArr = preg_split("/;|；/s",$statusSrc);
                $values = [];
                for($tempI  = 1; $tempI< count($statusArr); $tempI++){
                    $tempLine = $statusArr[$tempI];
                    $tempArr = preg_split("/::|：：/i",$tempLine);
                    $regAdmin = "/@admin/i";
                    $regNotStatus = "/^@/";//非status值
                    //echo "\r\n\r\n\$tempLine=$tempLine\r\n\r\n\r\n";
                    if(preg_match($regAdmin,$tempLine)){
                        $values[$tempArr[0]] = [$tempArr[1],'@admin'];
                    }else if(!preg_match($regNotStatus,$tempLine)){
                            if($tempArr[0] !== '') $values[$tempArr[0]] = [$tempArr[1],''];
                    }
                }
                //echo $values."\r\n";
                $statusField[$fName] = $values;
            }

            $reg = "/@foreign(.*)/i";
            if(preg_match($reg,$defaultAndComment,$tempMatch)){
                $tempArr = preg_split("/::|：：|;|'|；|,/i",$tempMatch[1]);
                $foreignField[$fName] = $tempArr[1];
            }

            $regUrl = "/@href[:：]{2}(.*)[;|；]{0,2}/i";
            if(preg_match($regUrl,$defaultAndComment,$tempMatch)){
                $tempMatch = explode("'",$tempMatch[1]);
                $hrefField[$fName] = $tempMatch[0];
            }
            //comment
            $tmpComment = preg_replace("/;/i",'; ',$matchComment[1]);
            $jiekouInfo[$fName] = "$fType //$tmpComment";

            //---search field----
            $reg = "/@search/i";
            if(preg_match($reg,$defaultAndComment)){
                $searchField[$fName] =  [$fType,$matchComment[1]];
            }

            //---@title field----
            $reg = "/@title/i";
            if(preg_match($reg,$defaultAndComment)){
                $titleField[$fName] =  [$fType,$matchComment[1]];
            }

        }//end for

        $regKey = "/PRIMARY KEY \(`(\w+)`/i";
        $key = '';
        $find = preg_match($regKey,$createSql,$match);
        if($find) {
            $key = $match[1];
        }else{
            $regKey = "/UNIQUE KEY `\w+` \(`(\w+)`\)/i";
            $find = preg_match($regKey,$createSql,$match);
            if(!$find){
                echo " <font color=red>no primary key or no single field UNIQUE key exists</font>";
            }else{
                $key = $match[1];
            }
        }

        if(defined('IS_ADMIN_SYS') && IS_ADMIN_SYS){
            $template = file(LIB_PATH.'model/tpl_admin.model.php');
        }else{
            $template = file(LIB_PATH.'model/tpl_front.model.php');
        }


        $modelContent = '';
        $modelPublic = '';

        ////@tag
        $allTags = $this->autoTag;
        if(IS_ADMIN_SYS){
            $allTags = array_merge($this->autoTag,$this->adminAutoTag);
        }
        $tagStr = "";
        foreach($allTags as $autoTag){
            $fields = $tagField[$autoTag];
            $tmpStr = $this->getStrByArr($fields);
            $tagStr .= "
    public static  function {$autoTag}Field()
    {
        return ".preg_replace("/[\r\n]+/s","",$tmpStr).";
    }
            ";
        }

        foreach($template as $line){
            $reg = "/\/\/TempDesc/";
            $options = JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES +JSON_PRETTY_PRINT;
            $line = preg_replace($reg,json_encode($jiekouInfo,$options),$line);

            $reg = "/\/\/TempDefaultValue/";
            $line = preg_replace($reg,$allField,$line);

            $reg = "/TempClassName/i";
            $line = preg_replace($reg,$className,$line);

            $reg = "/TempTable/i";
            $line = preg_replace($reg,$tableName,$line);

            $reg = "/TempKey/i";
            $line = preg_replace($reg,$key,$line);

            $reg = "/TempName/i";
            $line = preg_replace($reg,$className,$line);

            $reg = "/'TempField'/i";
            $line = preg_replace($reg,$this->getStrByArr($fieldInfo),$line);


            $reg = "/'TempAllDesc'/i";
            $line = preg_replace($reg,$this->getStrByArr($allFieldsDesc),$line);


            $reg = "/'TempStatus'/i";
            $line = preg_replace($reg,$this->getStrByArr($statusField),$line);

            $reg = "/'TempForeign'/i";
            $line = preg_replace($reg,$this->getStrByArr($foreignField),$line);

            $reg = "/'TempHref'/i";
            $line = preg_replace($reg,$this->getStrByArr($hrefField),$line);


            $reg = "/'TempSearch'/i";
            $line = preg_replace($reg,$this->getStrByArr($searchField),$line);


            $reg = "/\/\/@tag/";
            $line = preg_replace($reg,$tagStr,$line);


            $reg = "/'TempTitle'/i";
            $line = preg_replace($reg,$this->getStrByArr($titleField),$line);

            $modelContent .= $line;


            //--代码提示用----
            $reg = "/private/i";
            $publicLine = preg_replace($reg,'public',$line);
            $modelPublic  .= $publicLine;
        }

        $modelFileName = strtolower($className).'.model.php';
        $fileName = ROOT_PATH.'/model/'.$modelFileName;
        $fileName2 = ROOT_PATH.'/doc/model/'.$modelFileName;
        $this->saveToFile($fileName,$modelContent,true);
        $this->saveToFile($fileName2,$modelPublic,true);


        //----- 测试的html文件 ------
        $templateDev = file(LIB_PATH.'web/tpl_dev.html');
        $devContent = '';
        foreach($templateDev as $line){

            $reg = "/TempLower/i";
            $line = preg_replace($reg,strtolower($className),$line);
            $reg = "/TempDev/i";
            $line = preg_replace($reg,$contentDev,$line);

            $devContent .= $line;
        }
        $fileDev = ROOT_PATH.'web/dev/'.strtolower($className).'.html';
        $this->saveToFile($fileDev,$devContent,true);

        //扩展model
        if(defined('IS_ADMIN_SYS') && IS_ADMIN_SYS) {
            $modelFileNameExt = strtolower($className) . 'ext.model.php';
            $fileNameExt = ROOT_PATH. '/model/' . $modelFileNameExt;
            $template = file(LIB_PATH . "/model/tpl_adminext.model.php");
            $modelExtContent = '';
            foreach ($template as $line) {
                $reg = "/templower/i";
                $line = preg_replace($reg, strtolower($className), $line);

                $reg = "/TempName/i";
                $line = preg_replace($reg, $className, $line);
                $modelExtContent .= $line;
            }

            $this->saveToFile($fileNameExt, $modelExtContent, false);
        }//end 扩展model
    }

    private function getCreateSql($tableName){
        $db= db();
        $sql = 'SHOW CREATE TABLE `'.$tableName.'`';
        $tableInfo = $db->query($sql);
        $createSql = $tableInfo[0]['Create Table'];

        $reg = "/(=utf8\s+)|(\s+utf8\s+)/i";
        if(preg_match($reg,$createSql)){
            echo "<font color=red>$tableName 有utf8类型的字段，期望修改为utf8mb4_general_ci </font>";
        }

        return $createSql;
    }

    private function prepareDir(){
        $modelDir = ROOT_PATH.'/doc/model/';
        if(!file_exists($modelDir)){
            mkdir($modelDir);
        }
    }

    public function createAction(){
        if($_SERVER['PUBLIC']) die('public can\'t run ');

        $this->prepareDir();

        $badTableName = "/_ext$/i";

        $allTables = $this->getAllTables();
        foreach($allTables as $tableName){
            echo "\r\n $tableName  ";
            if(!$tableName) break;

            if(preg_match($badTableName,$tableName)){
                echo "<br /><font color='red'>bad table name,table name can't be ***_ext :</font>\r\n $tableName  ";
                break;
            }

            $this->createModel($tableName);
            if (defined('IS_ADMIN_SYS') && IS_ADMIN_SYS && IS_WINDOWS) {
                 $this->createCon($tableName);
                 $this->createListView($tableName);//只创建后天的view
                 $this->createEditView($tableName);
            }
        }//end createAction
        
    }//end createAction

    public function getTidyTemplate($templateFile,$fieldName,$fieldDesc=''){
        if(!$fieldDesc) $fieldDesc = $fieldName;
        $template = file_get_contents($templateFile);
        $template = preg_replace("/\{fieldName\}/",$fieldName,$template);
        $template = preg_replace("/\{fieldDesc\}/",$fieldDesc,$template);
        return "\r\n\r\n".$template;
    }
	
	
	public function getStrByArr($arr){
        if(!$arr) return '[]';
        return preg_replace("/[\r\n]+/s","",var_export($arr,true));
    }

    //后台图片占位符
    public function imageAction(){
        myimage::placeholder(r_int('width'),r_int('height'));
    }
}

